package com.atguigu.javase;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Author: shenhao
 * @CreatTime: 2024/10/5 14:47
 * @Version: 1.0
 * 深浅拷贝演示
 * clone方法是浅拷贝
 */
public class ShallowDeepCopyDemo implements Cloneable {
    public static void main(String[] args) throws CloneNotSupportedException {
//        ShallowDeepCopyDemo shallowDeepCopyDemo = new ShallowDeepCopyDemo();
//        Object clone = shallowDeepCopyDemo.clone();
//        System.out.println(clone.hashCode());
        m1();
    }

    private static void m1() throws CloneNotSupportedException {
        Emp emp = new Emp("z3",18,"雷军","Teo");
        System.out.println("emp = " + emp);
        Emp clone = (Emp) emp.clone();
        System.out.println("clone = " + clone);
        System.out.println();
        clone.getBoss().setTitle("CTO");
        System.out.println("-------------clone拷贝对象修改后,是否会改变原对象");
        System.out.println("clone = " + clone);
        System.out.println("emp = " + emp);
        System.out.println(emp.hashCode()+":   "+clone.hashCode());
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Boss implements Cloneable {
    private String bossName;
    private String title;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Emp implements Cloneable {
    private String empName;
    private Integer age;
    private Boss boss;
    public Emp(String empName, Integer age, String bossName,String title) {
        this.empName = empName;
        this.age = age;
        this.boss = new Boss(bossName,title);
    }

//    @Override
//    protected Object clone() throws CloneNotSupportedException {
//        return super.clone();
//    }

    @Override//深拷贝,生成一个新对象
    protected Object clone() throws CloneNotSupportedException {
        return new Emp(empName,age,boss.getBossName(),boss.getTitle());
    }
}